#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
#
# This file is part of Coruja-scripts
#
# Coruja-scripts is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Coruja-scripts is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Coruja-scripts.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2011 Grupo Falabrasil - http://www.laps.ufpa.br/falabrasil
#
# Author 2011: Pedro Batista - pedosb@gmail.com

import subprocess
import re
import argparse

import pyinotify

import reverse

TORQUE_LOG_FILE = '/var/log/pbs_server.log'
wm = pyinotify.WatchManager()

class JobWait(pyinotify.ProcessEvent):
	def __init__(self, job_id):
		super(JobWait, self).__init__()
		self.job_id = job_id
		self.exited = False
		self.exit_status = False

	def process_IN_MODIFY(self, event):
		f = open(event.path)
		job_line_pattern = \
				'^.+;(?P<origin>(0008)|(0010));PBS_Server;Job;%s.*;(?P<mes>.+)$'\
				% self.job_id
		queued_pattern = '^Job Queued.*$'
		exit_pattern = '^Exit_status=(?P<status>-?\d+).*$'

		for line in reverse.xreverse(f):
			match = re.search(job_line_pattern, line)
			if match is None:
				continue

			origin = match.group('origin')
			message = match.group('mes')
			queued_match = re.search(queued_pattern, message)

			if queued_match is not None and origin == '0008':
				break
			elif origin == '0010':
				exit_match = re.search(exit_pattern, message)
				if exit_match is None:
					print 'ERROR'
				self.exit_status = exit_match.group('status')
				self.exited = True

def exec_wait_pbs(command):
	job_id = subprocess.check_output(command, shell=True, universal_newlines=True).strip()
	print job_id
	job_wait = JobWait(job_id)

	notifier = pyinotify.Notifier(wm, job_wait)
	wm.add_watch(TORQUE_LOG_FILE,
			pyinotify.EventsCodes.ALL_FLAGS['IN_MODIFY'])

	while True:  # loop forever
		# process the queue of events as explained above
		notifier.process_events()
		if job_wait.exited:
			notifier.stop()
			return job_wait.exit_status
		if notifier.check_events():
			# read notified events and enqeue them
			notifier.read_events()

def find_acc(hresults_output_file):
	f = open(hresults_output_file)
	pattern='^WORD: %Corr=\d\d\.\d\d, Acc=(?P<acc>\d\d\.\d\d) \[H=\d+, D=\d+, S=\d+, I=\d+, N=\d+\]$'
	m = re.search(pattern, ''.join(f.readlines()), flags=re.MULTILINE)
	f.close()
	return float(m.group('acc'))

my_cmd = '../scripts_train/hdecode_run/run_hdecode.sh -v "-C confs/hdecode.conf -t 250.0 -s 20.0 -p 22.0 -v 100.0 -n 8 -a 1.5 -H model/cd_tied_14g_mmi/hmmdefs -w etc/60k_plus_train-nova.arpa etc/60k_plus_train_ssp.dic etc/tiedlist -S etc/mfc_test_20.txt" -r "-I /projetos/bravoz/LVCSR-Project/databases/LapsBenchMark/words.mlf etc/60k_plus_train_ssp.dic" -o result_mmi_60k/ -n 2 -l logdir/result_mmi_60k'
print exec_wait_pbs(my_cmd)

if __name__=='__main__':
	pass
#	parser = argparse.ArgumentParser(description='')
#	parser.add_argument('-', '--',
#			help='')
#	args = parser.parse_args()
